<template>
    <div class="activity-publish">
        <div class="publish-container" v-loading="loading">
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <span class="card-title">{{ isEdit ? '编辑学术活动' : '发布学术活动' }}</span>
                </div>

                <el-form ref="activityForm" :model="activityForm" :rules="activityRules" label-width="120px"
                    class="activity-form">
                    <el-form-item label="活动标题" prop="title">
                        <el-input v-model="activityForm.title" placeholder="请输入活动标题" maxlength="100" show-word-limit />
                    </el-form-item>

                    <el-form-item label="活动类型" prop="type">
                        <el-select v-model="activityForm.type" placeholder="请选择活动类型">
                            <el-option label="讲座" :value="1" />
                            <el-option label="赛事" :value="2" />
                            <el-option label="培训" :value="3" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="活动内容" prop="content">
                        <el-input v-model="activityForm.content" type="textarea" :rows="4" placeholder="请输入活动内容"
                            maxlength="500" show-word-limit />
                    </el-form-item>

                    <el-form-item label="活动地点" prop="location">
                        <el-input v-model="activityForm.location" placeholder="请输入活动地点" maxlength="100" />
                    </el-form-item>

                    <el-form-item label="开始时间" prop="startTime">
                        <el-date-picker v-model="activityForm.startTime" type="datetime" placeholder="选择开始时间"
                            format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
                    </el-form-item>

                    <el-form-item label="结束时间" prop="endTime">
                        <el-date-picker v-model="activityForm.endTime" type="datetime" placeholder="选择结束时间"
                            format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
                    </el-form-item>

                    <el-form-item label="报名截止时间" prop="registrationDeadline">
                        <el-date-picker v-model="activityForm.registrationDeadline" type="datetime"
                            placeholder="选择报名截止时间" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
                    </el-form-item>

                    <el-form-item label="参与人数限制">
                        <el-switch v-model="hasParticipantLimit" active-text="限制人数" inactive-text="不限制" />
                    </el-form-item>

                    <el-form-item v-if="hasParticipantLimit" label="最大参与人数" prop="maxParticipants">
                        <el-input-number v-model="activityForm.maxParticipants" :min="1" :max="1000"
                            placeholder="请输入最大参与人数" />
                    </el-form-item>

                    <el-form-item label="活动要求">
                        <el-input v-model="activityForm.requirements" type="textarea" :rows="3"
                            placeholder="请输入参与活动的要求（可选）" maxlength="300" show-word-limit />
                    </el-form-item>


                    <el-form-item label="活动附件">
                        <el-upload class="upload-demo" action="#" :on-preview="handleAttachmentPreview"
                            :on-remove="handleAttachmentRemove" :before-upload="beforeAttachmentUpload"
                            :file-list="attachmentFileList" :limit="2" :on-exceed="handleAttachmentExceed"
                            :http-request="handleAttachmentUpload">
                            <el-button size="small" type="primary">
                                <i class="el-icon-upload2" />
                                上传活动附件
                            </el-button>
                            <div slot="tip" class="el-upload__tip">
                                只支持上传PDF、Word文档，用于提供活动详细信息和参考资料<br>
                                单个文件不超过10MB，最多上传2个文件
                            </div>
                        </el-upload>
                        <div v-if="attachmentFileList.length > 0" class="file-list-preview">
                            <div class="file-list-title">已上传文件：</div>
                            <div v-for="(file, index) in attachmentFileList" :key="index" class="file-item-preview">
                                <i :class="getFileIcon(file.name)" class="file-icon"></i>
                                <div class="file-info">
                                    <div class="file-name">{{ file.name }}</div>
                                    <div class="file-details">
                                        <span class="file-size">{{ formatFileSize(file.size) }}</span>
                                        <span class="file-type">{{ file.fileType && file.fileType.toUpperCase()
                                        }}</span>
                                        <span class="file-status" :class="file.status">{{ file.status === 'success' ?
                                            '上传成功' : '上传中' }}</span>
                                    </div>
                                </div>
                                <el-button type="text" size="mini" @click="previewFile(file)" class="preview-btn">
                                    预览
                                </el-button>
                            </div>
                        </div>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" :loading="submitLoading" @click="submitForm">
                            {{ isEdit ? '更新活动' : '发布活动' }}
                        </el-button>
                        <el-button @click="resetForm">重置</el-button>
                        <el-button @click="handleCancel">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script>
import { uploadFile } from '@/api/upload';
import { publishActivity, getActivityDetail, updateActivity } from '@/api/activity';
export default {
    name: 'ActivityPublish',
    data() {
        const validateEndTime = (rule, value, callback) => {
            if (value && this.activityForm.startTime) {
                if (new Date(value) <= new Date(this.activityForm.startTime)) {
                    callback(new Error('结束时间必须晚于开始时间'))
                } else {
                    callback()
                }
            } else {
                callback()
            }
        }

        const validateRegistrationDeadline = (rule, value, callback) => {
            if (value && this.activityForm.startTime) {
                if (new Date(value) >= new Date(this.activityForm.startTime)) {
                    callback(new Error('报名截止时间必须早于活动开始时间'))
                } else {
                    callback()
                }
            } else {
                callback()
            }
        }

        return {
            isEdit: false,
            activityId: null,
            loading: false,
            activityForm: {
                title: '',
                type: '',
                content: '',
                location: '',
                startTime: '',
                endTime: '',
                registrationDeadline: '',
                maxParticipants: null,
                requirements: ''
            },
            activityRules: {
                title: [
                    { required: true, message: '请输入活动标题', trigger: 'blur' },
                    { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
                ],
                type: [
                    { required: true, message: '请选择活动类型', trigger: 'change' }
                ],
                content: [
                    { required: true, message: '请输入活动内容', trigger: 'blur' },
                    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
                ],
                location: [
                    { required: true, message: '请输入活动地点', trigger: 'blur' }
                ],
                startTime: [
                    { required: true, message: '请选择开始时间', trigger: 'change' }
                ],
                endTime: [
                    { required: true, message: '请选择结束时间', trigger: 'change' },
                    { validator: validateEndTime, trigger: 'change' }
                ],
                registrationDeadline: [
                    { required: true, message: '请选择报名截止时间', trigger: 'change' },
                    { validator: validateRegistrationDeadline, trigger: 'change' }
                ],
                maxParticipants: [
                    { type: 'number', message: '请输入正确的数字', trigger: 'blur' }
                ]
            },
            hasParticipantLimit: false,
            submitLoading: false,
            attachmentFileList: []
        }
    },
    created() {
        // 检查是否是编辑模式
        this.activityId = this.$route.query.id
        if (this.activityId) {
            this.isEdit = true
            this.loadActivityData()
        }
    },
    watch: {
        hasParticipantLimit(val) {
            if (!val) {
                this.activityForm.maxParticipants = null
            }
        }
    },
    methods: {
        // 加载活动数据（编辑模式）
        async loadActivityData() {
            try {
                this.loading = true
                // 调用获取活动详情的API
                const res = await getActivityDetail(this.activityId)
                const activity = res.data

                // 填充表单数据
                this.activityForm = {
                    title: activity.title,
                    type: activity.activityType,
                    content: activity.content,
                    location: activity.location,
                    startTime: activity.startTime,
                    endTime: activity.endTime,
                    registrationDeadline: activity.registrationDeadline,
                    maxParticipants: activity.maxParticipants,
                    requirements: activity.requirements || ''
                }

                // 设置人数限制开关
                this.hasParticipantLimit = !!activity.maxParticipants

                // 处理附件
                if (activity.attachmentUrl) {
                    try {
                        const attachments = JSON.parse(activity.attachmentUrl)
                        this.attachmentFileList = attachments.map((file, index) => ({
                            ...file,
                            uid: Date.now() + index,
                            status: 'success'
                        }))
                    } catch (e) {
                        console.error('解析附件数据失败:', e)
                    }
                }

            } catch (error) {
                console.error('加载活动数据失败:', error)
            } finally {
                this.loading = false
            }
        },
        submitForm() {
            this.$refs.activityForm.validate(async (valid) => {
                if (valid) {
                    this.submitLoading = true
                    const formData = {
                        title: this.activityForm.title,
                        content: this.activityForm.content,
                        location: this.activityForm.location,
                        startTime: this.activityForm.startTime,
                        endTime: this.activityForm.endTime,
                        registrationDeadline: this.activityForm.registrationDeadline,
                        maxParticipants: this.hasParticipantLimit ? this.activityForm.maxParticipants : null,
                        activityType: this.activityForm.type, // 已经是数字类型
                        status: 1, // 1-发布状态
                        attachmentUrl: JSON.stringify(this.attachmentFileList), // 附件URL数组
                        requirements: this.activityForm.requirements // 活动要求
                    }

                    // 如果是编辑模式，添加活动ID
                    if (this.isEdit) {
                        formData.id = this.activityId
                    }

                    try {
                        console.log(this.isEdit ? '更新活动数据:' : '发布活动数据:', formData)

                        if (this.isEdit) {
                            // 调用更新活动API
                            const res = await updateActivity(formData);
                            this.$message.success('活动更新成功');
                        } else {
                            // 调用发布活动API
                            const res = await publishActivity(formData);
                            this.$message.success(res.data || '活动发布成功');
                        }
                        this.$router.push('/activity/manage')
                    } catch (error) {
                        console.log(error);
                    } finally {
                        this.submitLoading = false
                    }
                } else {
                    this.submitLoading = false
                    return false;
                }
            })
        },
        resetForm() {
            this.$refs.activityForm.resetFields()
            this.hasParticipantLimit = false
            this.attachmentFileList = []
        },
        handleCancel() {
            this.$confirm('确认取消发布活动？未保存的数据将丢失', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '继续编辑',
                type: 'warning'
            }).then(() => {
                // 返回到活动管理页面
                this.$router.push('/activity/manage')
            }).catch(() => {
                // 用户选择继续编辑，不做任何操作
            })
        },
        // 活动附件上传相关方法
        handleAttachmentPreview(file) {
            // 根据文件类型进行预览或下载
            if (file.url) {
                window.open(file.url, '_blank')
            } else {
                this.$message.info('文件预览功能开发中...')
            }
        },
        // 预览文件方法
        previewFile(file) {
            if (file.url) {
                window.open(file.url, '_blank')
            } else {
                this.$message.info('文件URL不存在，无法预览')
            }
        },
        handleAttachmentRemove(file, fileList) {
            this.attachmentFileList = fileList
        },
        beforeAttachmentUpload(file) {
            const allowedTypes = [
                'application/pdf',
                'application/msword',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            ]
            const isAllowedType = allowedTypes.includes(file.type)
            const isLt10M = file.size / 1024 / 1024 < 10

            if (!isAllowedType) {
                this.$message.error('只能上传 PDF、Word 格式的文件!')
            }
            if (!isLt10M) {
                this.$message.error('文件大小不能超过 10MB!')
            }
            return isAllowedType && isLt10M
        },
        // 自定义文件上传方法
        async handleAttachmentUpload(options) {
            const { file, onSuccess, onError, onProgress } = options

            try {
                // 创建FormData对象
                const formData = new FormData()
                formData.append('file', file)
                // 调用上传API
                const response = await uploadFile(formData)
                const fileObj = {
                    ...response.data,
                    size: file.size,
                    originalName: file.name,
                    status: 'success',
                    uid: file.uid,
                    uploadTime: new Date().getTime(),
                }
                // 添加到附件列表数组
                this.attachmentFileList.push(fileObj)

                // 调用成功回调
                onSuccess(response.data, file)

                this.$message.success('文件上传成功!')

                // 打印完整的文件信息用于调试
                console.log('上传成功的文件信息:', fileObj)
            } catch (error) {
                console.error('文件上传错误:', error)
                onError(error)
                this.$message.error('文件上传失败!')
            }
        },
        handleAttachmentExceed(files, fileList) {
            this.$message.warning(`最多只能上传2个文件，当前已有${fileList.length}个文件`)
        },
        getFileIcon(fileName) {
            const ext = fileName.split('.').pop().toLowerCase()
            const iconMap = {
                pdf: 'el-icon-document',
                doc: 'el-icon-document',
                docx: 'el-icon-document'
            }
            return iconMap[ext] || 'el-icon-document'
        },
        formatFileSize(bytes) {
            if (bytes === 0) return '0 B'
            const k = 1024
            const sizes = ['B', 'KB', 'MB', 'GB']
            const i = Math.floor(Math.log(bytes) / Math.log(k))
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
        },
        // 获取完整的附件数据用于表单提交
        getAttachmentData() {
            return this.attachmentFileList.map(file => ({
                // 后端返回的核心数据
                name: file.name,
                url: file.url,
                fileType: file.fileType,
                // 前端补充的数据
                size: file.size,
                originalName: file.originalName,
                uploadTime: file.uploadTime,
            }))
        }
    }
}
</script>

<style lang="scss" scoped>
.activity-publish {
    padding: 20px;
}

.publish-container {
    max-width: 800px;
    margin: 0 auto;
}

.card-title {
    font-size: 18px;
    font-weight: bold;
    color: #303133;
}

.activity-form {
    .el-form-item {
        margin-bottom: 22px;
    }

    .el-select,
    .el-date-picker {
        width: 100%;
    }
}

.upload-demo {
    .el-upload__tip {
        color: #606266;
        font-size: 12px;
        margin-top: 7px;
        line-height: 1.4;
    }

    .el-button {
        margin-bottom: 10px;
    }

    // 文件列表样式优化
    ::v-deep .el-upload-list {
        .el-upload-list__item {
            border: 1px solid #e4e7ed;
            border-radius: 6px;
            margin-top: 10px;

            &:hover {
                background-color: #f5f7fa;
            }
        }

        .el-upload-list__item-name {
            color: #606266;
            font-size: 14px;
        }

        .el-icon-document,
        .el-icon-close {
            font-size: 16px;
        }
    }
}

.file-list-preview {
    margin-top: 15px;
    padding: 12px;
    background-color: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e4e7ed;

    .file-list-title {
        font-size: 14px;
        font-weight: 500;
        color: #303133;
        margin-bottom: 10px;
    }

    .file-item-preview {
        display: flex;
        align-items: center;
        padding: 8px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
            border-bottom: none;
        }

        .file-icon {
            font-size: 18px;
            margin-right: 12px;
            color: #409eff;
            flex-shrink: 0;
        }

        .file-info {
            flex: 1;

            .file-name {
                color: #303133;
                font-size: 14px;
                font-weight: 500;
                margin-bottom: 4px;
            }

            .file-details {
                display: flex;
                gap: 12px;

                .file-size {
                    color: #909399;
                    font-size: 12px;
                }

                .file-type {
                    color: #67c23a;
                    font-size: 12px;
                    font-weight: 500;
                }

                .file-status {
                    font-size: 12px;

                    &.success {
                        color: #67c23a;
                    }

                    &.uploading {
                        color: #e6a23c;
                    }
                }
            }
        }

        .preview-btn {
            color: #409eff;
            padding: 0;
            margin-left: 8px;

            &:hover {
                color: #66b1ff;
            }
        }
    }
}
</style>
